﻿using Dapper;
using FullCoreDBModels;
using Newtonsoft.Json;
using Oracle.ManagedDataAccess.Client;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace FullCoreRepository
{
    public class InterfaceToolRepository
    {
        #region 变量

        /// <summary>
        /// 删除接口sql语句
        /// 李亚辉 2022年3月24日
        /// </summary>
        private readonly string deleteInterfaceToolSql;

        /// <summary>
        /// 新增接口sql语句
        /// 李亚辉 2022年3月24日
        /// </summary>
        private readonly string insertInterfaceToolSql;

        /// <summary>
        /// 更新接口sql语句
        /// 李亚辉 2022年3月24日
        /// </summary>
        private readonly string updateInterfaceToolSql;

        /// <summary>
        /// 更新接口不更新clob字段信息sql语句
        /// 李亚辉 2022年3月24日
        /// </summary>
        private readonly string updateInterfaceNoClobSql;

        /// <summary>
        /// 查询所有接口sql语句
        /// 李亚辉 2022年3月24日
        /// </summary>
        private readonly string selectAllSql;

        #endregion

        #region 构造函数

        /// <summary>
        /// 构造函数 李亚辉 2022年3月24日
        /// </summary>
        /// <exception cref="Exception"></exception>
        public InterfaceToolRepository()
        {
            var jsonFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "JsonSql", "InterfaceTool.json");
            var orderJsonSqls = JsonConvert.DeserializeObject<List<JsonSql>>(File.ReadAllText(jsonFile));
            if (orderJsonSqls.Any())
            {
                deleteInterfaceToolSql = orderJsonSqls.FirstOrDefault(a => a.SqlKey.Equals("deleteInterfaceToolSql"))
                    ?.SqlValue;
                insertInterfaceToolSql = orderJsonSqls.FirstOrDefault(a => a.SqlKey.Equals("insertInterfaceToolSql"))
                    ?.SqlValue;
                updateInterfaceToolSql = orderJsonSqls.FirstOrDefault(a => a.SqlKey.Equals("updateInterfaceToolSql"))
                    ?.SqlValue;
                updateInterfaceNoClobSql = orderJsonSqls
                    .FirstOrDefault(a => a.SqlKey.Equals("updateInterfaceNoClobSql"))
                    ?.SqlValue;
                selectAllSql = orderJsonSqls.FirstOrDefault(a => a.SqlKey.Equals("selectAllInterfaceSql"))?.SqlValue;
            }
            else
            {
                throw new Exception("InterfaceTool.json语句文件加载出错！");
            }
        }

        #endregion

        #region 方法

        /// <summary>
        /// 增加获取所有接口方法，sql语句读取jsonsql配置文件
        /// 李亚辉 2022年3月24日
        /// </summary>
        /// <returns></returns>
        public async Task< List<InterfaceToolEntity>> GetAllInterfaceTool()
        {
            var conditions = new List<ConditionArgs>();
            return await GetInterfaceTool(conditions, selectAllSql);
        }

        public async Task<InterfaceToolEntity> GetInterfaceToolByCode(string interfaceCode)
        {
            var conditions = new List<ConditionArgs>();
            conditions.Add(new ConditionArgs()
            {
                Key = "INTERFACECODE",
                Value = interfaceCode,
                JudgeType = JudgmentEnum.Equal,
                PreConnector = ConnectorEnum.And
            });
            var datas= await GetInterfaceTool(conditions);
            return datas.FirstOrDefault();
        }

        /// <summary>
        /// 获取接口list通用方法
        /// 李亚辉 2022年3月24日
        /// </summary>
        /// <param name="conditions">检索条件</param>
        /// <param name="defSql">默认查询sql语句</param>
        /// <returns>接口list</returns>
        public async Task<List<InterfaceToolEntity>> GetInterfaceTool(List<ConditionArgs> conditions, string defSql = "")
        {
            if (conditions != null)
            {
                var where = ConditionArgsHelper.JoinSQLStr(conditions.ToArray());
                string sql = string.IsNullOrEmpty(defSql) ? "SELECT * FROM INTERFACE_TOOL where 1=1 " : defSql;
                if (!string.IsNullOrEmpty(where))
                {
                    sql = sql + where;
                }
                using (var con = DapperFactory.CreateDefaultConnection())
                {
                    var result = await con.QueryAsync<InterfaceToolEntity>(sql);

                    return result.ToList();
                }
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 保存接口方法
        /// 李亚辉 2022年3月24日
        /// </summary>
        /// <param name="interfaces">接口list</param>
        /// <returns><see cref="CommonResult"/></returns>
        public CommonResult SaveInterfaceTool(List<InterfaceToolEntity> interfaces)
        {
            var result = new CommonResult();

            try
            {
                using (var conn = DapperFactory.CreateDefaultConnection())
                {
                    var tran = conn.BeginTransaction();
                    try
                    {
                        interfaces.ForEach(a =>
                        {
                            if (a.ISDELETE == 1)
                            {
                                conn.Execute(deleteInterfaceToolSql, new { a.ID }, tran);
                            }
                            else if (!string.IsNullOrEmpty(a.ID))
                            {
                                conn.Execute(updateInterfaceToolSql, a,tran);

                                //var cmd = conn.CreateCommand();
                                //cmd.CommandText = updateInterfaceToolSql;
                                //cmd.Transaction = tran;
                                //var param = new OracleParameter[]
                                //{
                                //    new OracleParameter(":INTERFACECODE", OracleDbType.NVarchar2)
                                //        { Value = a.INTERFACECODE },
                                //    new OracleParameter(":INTERFACENAME", OracleDbType.NVarchar2)
                                //        { Value = a.INTERFACENAME },
                                //    new OracleParameter(":INVALIDFLAG", OracleDbType.Long) { Value = a.INVALIDFLAG },
                                //    new OracleParameter(":INTERFACEDESCRIPTION", OracleDbType.NVarchar2)
                                //        { Value = a.INTERFACEDESCRIPTION },
                                //    new OracleParameter(":UPDATEDATE", OracleDbType.Date) { Value = a.UPDATEDATE },
                                //    new OracleParameter(":UPDATEUSER", OracleDbType.NVarchar2) { Value = a.UPDATEUSER },
                                //    new OracleParameter(":INJSON", OracleDbType.Clob) { Value = a.INJSON },
                                //    new OracleParameter(":JAVASCRIPTCODE", OracleDbType.Clob)
                                //        { Value = a.JAVASCRIPTCODE },
                                //    new OracleParameter(":OUTJSON", OracleDbType.Clob) { Value = a.OUTJSON },
                                //    new OracleParameter(":CLASSNAME", OracleDbType.NVarchar2) { Value = a.CLASSNAME },
                                //    new OracleParameter(":FUNCTIONNAME", OracleDbType.NVarchar2)
                                //        { Value = a.FUNCTIONNAME },
                                //    new OracleParameter(":SCRIPTTYPE", OracleDbType.Long) { Value = a.SCRIPTTYPE },
                                //    new OracleParameter(":ID", OracleDbType.NVarchar2, 36) { Value = a.ID },
                                //};
                                //var oracmd = cmd as OracleCommand;
                                //oracmd.Parameters.AddRange(param);
                                //oracmd.ExecuteNonQuery();
                            }
                            else if (string.IsNullOrEmpty(a.ID))
                            {
                                a.ID = Guid.NewGuid().ToString();
                                conn.Execute(insertInterfaceToolSql, a, tran);

                                //var cmd = conn.CreateCommand();
                                //cmd.CommandText = insertInterfaceToolSql;
                                //cmd.Transaction = tran;
                                //var param = new OracleParameter[]
                                //{
                                //    new OracleParameter(":ID", OracleDbType.NVarchar2) { Value = a.ID },
                                //    new OracleParameter(":INTERFACECODE", OracleDbType.NVarchar2)
                                //        { Value = a.INTERFACECODE },
                                //    new OracleParameter(":INTERFACENAME", OracleDbType.NVarchar2)
                                //        { Value = a.INTERFACENAME },
                                //    new OracleParameter(":INTERFACEDESCRIPTION", OracleDbType.NVarchar2)
                                //        { Value = a.INTERFACEDESCRIPTION },
                                //    new OracleParameter(":CREATEDATE", OracleDbType.Date) { Value = a.CREATEDATE },
                                //    new OracleParameter(":CREATEUSER", OracleDbType.NVarchar2) { Value = a.CREATEUSER },
                                //    new OracleParameter(":UPDATEDATE", OracleDbType.Date) { Value = a.UPDATEDATE },
                                //    new OracleParameter(":UPDATEUSER", OracleDbType.NVarchar2) { Value = a.UPDATEUSER },
                                //    new OracleParameter(":INJSON", OracleDbType.Clob) { Value = a.INJSON },
                                //    new OracleParameter(":JAVASCRIPTCODE", OracleDbType.Clob)
                                //        { Value = a.JAVASCRIPTCODE },
                                //    new OracleParameter(":OUTJSON", OracleDbType.Clob) { Value = a.OUTJSON },
                                //    new OracleParameter(":CLASSNAME", OracleDbType.NVarchar2) { Value = a.CLASSNAME },
                                //    new OracleParameter(":FUNCTIONNAME", OracleDbType.NVarchar2)
                                //        { Value = a.FUNCTIONNAME },
                                //    new OracleParameter(":SCRIPTTYPE", OracleDbType.Long) { Value = a.SCRIPTTYPE }
                                //};
                                //var oracmd = cmd as OracleCommand;
                                //oracmd.Parameters.AddRange(param);
                                //oracmd.ExecuteNonQuery();
                            }
                        });

                        tran.Commit();
                    }
                    catch (Exception ex)
                    {
                        tran.Rollback();
                        result.Result = false;
                        result.ErrMsg = ex.Message;
                        LogerHelper.GetLog().Error(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                result.Result = false;
                result.ErrMsg = ex.Message;
                LogerHelper.GetLog().Error(ex);
            }

            return result;
        }

        /// <summary>
        /// 保存接口方法,不保存blog字段，方便维护分类信息等
        /// 李亚辉 2022年3月24日
        /// </summary>
        /// <param name="interfaces">接口list</param>
        /// <returns><see cref="CommonResult"/></returns>
        public CommonResult SaveInterfaceToolNoBlob(List<InterfaceToolEntity> interfaces)
        {
            var result = new CommonResult();

            try
            {
                using (var conn = DapperFactory.CreateDefaultConnection())
                {
                    var tran = conn.BeginTransaction();
                    try
                    {
                        interfaces.ForEach(a =>
                        {
                            if (a.ISDELETE == 1)
                            {
                                conn.Execute(deleteInterfaceToolSql, new { a.ID }, tran);
                            }
                            else if (!string.IsNullOrEmpty(a.ID))
                            {
                                conn.Execute(updateInterfaceNoClobSql, a, tran);
                            }
                        });

                        tran.Commit();
                    }
                    catch (Exception ex)
                    {
                        tran.Rollback();
                        result.Result = false;
                        result.ErrMsg = ex.Message;
                        LogerHelper.GetLog().Error(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                result.Result = false;
                result.ErrMsg = ex.Message;
                LogerHelper.GetLog().Error(ex);
            }

            return result;
        }

        #endregion
    }
}